// src/components/PreferenceModal.jsx
import React, { useState } from "react";
import {
  Paper,
  Typography,
  FormControlLabel,
  Checkbox,
  Button,
  Box,
  Grid,
  IconButton
} from '@mui/material';
import CloseIcon from '@mui/icons-material/Close';
import { submitLikes } from "../api/user";

// 偏好类别数据
const preferenceData = {
  "音乐": ["流行", "摇滚", "乡村", "爵士", "古典", "原声", "纯音乐", "舞曲", "说唱"],
  "体育": ["足球", "篮球", "网球", "台球", "棒球", "NFL", "橄榄球", "F1"],
  "游戏": ["赛车游戏", "格斗游戏", "体育游戏", "战略游戏", "角色扮演", "动作游戏", "冒险游戏", "射击游戏", "桌面游戏", "益智游戏", "养成游戏", "卡片游戏", "即时战略游戏", "第一人称射击游戏", "动作角色扮演游戏", "战略角色扮演游戏", "在线角色扮演", "音乐游戏", "文字AVG", "模拟游戏", "视频"],
  "剧集": ["剧情", "喜剧", "家庭", "动作", "运动", "冒险", "爱情", "科幻", "奇幻", "动画", "音乐", "纪录", "传记", "历史", "战争", "西部", "灾难", "犯罪", "悬疑", "恐怖", "惊悚", "舞蹈"],
  "电影": ["剧情", "喜剧", "家庭", "动作", "运动", "冒险", "爱情", "科幻", "奇幻", "动画", "音乐", "纪录", "传记", "历史", "战争", "西部", "灾难", "犯罪", "悬疑", "恐怖", "惊悚", "舞蹈"],
  "动漫": [
    "原创", "漫画改", "小说改", "游戏改", "特摄", "布袋戏", "热血", "穿越", "奇幻", "战斗", "搞笑", "日常", "科幻", "萌系", "治愈", "校园", "少儿", "泡面", "恋爱", "少女",
    "魔法", "冒险", "历史", "架空", "机战", "神魔", "声控", "运动", "励志", "音乐",
    "推理", "社团", "智斗", "催泪", "美食", "偶像", "乙女", "职场"
  ],
  "学习": ["计算机", "外语", "考研", "课件", "开放课程", "人文社会", "自然科学", "理工类"],
  "综艺": ["新闻访谈", "盛会典礼", "综艺娱乐", "音乐现场"]
};

export default function PreferenceModal({ show, onClose }) {
  // 每个大类独立保存所选小类
  const [selected, setSelected] = useState({});

  const toggleSelection = (category, sub) => {
    setSelected((prev) => {
      const prevSubs = prev[category] || [];
      const newSubs = prevSubs.includes(sub)
        ? prevSubs.filter((s) => s !== sub)
        : [...prevSubs, sub];

      return {
        ...prev,
        [category]: newSubs
      };
    });
  };

  const handleSubmit = async () => {
    try {
      await submitLikes(selected);  // 提交嵌套对象
      onClose();
    } catch (err) {
      console.error("提交失败", err);
    }
  };

  if (!show) return null;

  return (
    <Box
      sx={{
        position: 'fixed',
        top: 0,
        left: 0,
        width: '100vw',
        height: '100vh',
        bgcolor: 'rgba(0, 0, 0, 0.4)',
        zIndex: 1300,
        display: 'flex',
        alignItems: 'center',
        justifyContent: 'center',
        backdropFilter: 'blur(2px)',
      }}
    >
      <Paper
        elevation={6}
        sx={{
          width: '80%',
          maxWidth: 900,
          maxHeight: '85vh',
          overflowY: 'auto',
          borderRadius: 3,
          padding: 4,
          bgcolor: 'white',
        }}
      >
        <Box display="flex" justifyContent="space-between" alignItems="center" mb={2}>
          <Typography variant="h5" fontWeight="bold">
            选择你感兴趣的内容
          </Typography>
          <IconButton onClick={onClose}>
            <CloseIcon />
          </IconButton>
        </Box>

        {Object.entries(preferenceData).map(([mainCategory, subcategories]) => (
          <Box key={mainCategory} mb={3}>
            <Typography variant="subtitle1" fontWeight="bold" color="primary" gutterBottom>
              {mainCategory}
            </Typography>
            <Grid container spacing={1}>
              {subcategories.map((sub) => (
                <Grid item xs={6} sm={4} md={3} key={sub}>
                  <FormControlLabel
                    control={
                      <Checkbox
                        checked={selected[mainCategory]?.includes(sub) || false}
                        onChange={() => toggleSelection(mainCategory, sub)}
                      />
                    }
                    label={sub}
                  />
                </Grid>
              ))}
            </Grid>
          </Box>
        ))}

        <Box mt={3} display="flex" justifyContent="flex-end" gap={2}>
          <Button variant="outlined" color="inherit" onClick={onClose}>
            跳过
          </Button>
          <Button variant="contained" color="primary" onClick={handleSubmit}>
            提交
          </Button>
        </Box>
      </Paper>
    </Box>
  );
}
